package com.zhao.system.Controller;


import com.zhao.system.poro.User;
import com.zhao.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import response.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaozhao
 * @since 2020-11-08
 */
@CrossOrigin(allowCredentials ="true")
@RestController
@RequestMapping("user")
@Transactional
public class UserController {
    @Autowired
    UserService userService;
    //查询用户是否存在,进行注册
    @RequestMapping("/regist")
    public Result Regist(@RequestBody User user, HttpSession session){
        User users = userService.find(user);
        if(users!=null){
            return Result.error().data("message","用户已存在");
        }
        int id = userService.add(user);
        session.setAttribute("id",id);
        return Result.ok();
    }

    //检验登录
    @RequestMapping("/login")
    public Result Login(@RequestBody User user, HttpServletRequest request){
        HttpSession session = request.getSession();
        User userList = userService.find(user);
        System.out.println("userList========="+userList);
        if(userList!=null){
            session.setAttribute("user",userList);
            return Result.ok().data("user",user.getUsername());
        }
        return Result.error().data("message","用户名或密码错误");
    }

    //检测用户名是否存在
    @RequestMapping("/check")
    public  Result check(@RequestParam("username")String username){
        User user = userService.findbyname(username);
        if(user==null){
            return Result.error().data("message","用户不存在");
        }
        return Result.ok();
    }

    //通过id查询用户名和密码
    @RequestMapping("/find")
    public Result find(HttpSession session){
        User user = (User) session.getAttribute("user");
        User user1 = userService.getById(user.getId());
        return Result.ok().data("user",user1);
    }

    //通过id修改密码
    @RequestMapping("/update")
    public Result update(@RequestBody User user){
        userService.updateById(user);
        return Result.ok();
    }

}

